<template>
  <div class="center-container">
    <el-card class="center-card">
      <template #header>
        <div class="card-header">
          <h3>个人信息</h3>
        </div>
      </template>
      
      <div class="user-info">
        <!-- <div class="avatar-container"> 头像
          <el-avatar :size="100" :src="userInfo.headImg || '/assets/img/avator.png'" />
          <div class="upload-btn">
            <el-upload
              class="avatar-uploader"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleAvatarChange"
            >
              <el-button size="small" type="primary">更换头像</el-button>
            </el-upload>
          </div>
        </div> -->
        
        <el-form
          ref="formRef"
          :model="userInfo"
          label-width="100px"
          class="user-form"
        >        
     
          <!-- 根据不同角色显示不同字段 -->
          <template v-if="role === '学生'">

            <el-form-item label="学生账号">
              <el-input v-model="userInfo.xueshengzhanghao" :disabled="true" />
            </el-form-item>

            <!-- <el-form-item label="用户名">
              <el-input v-model="userInfo.xueshengzhanghao" :disabled="true" />
            </el-form-item> -->

            <el-form-item label="姓名">
              <el-input v-model="userInfo.xueshengxingming" />
            </el-form-item>

            <el-form-item label="性别">
              <el-input v-model="userInfo.xingbie" />
            </el-form-item>

            <el-form-item label="年龄">
              <el-input v-model="userInfo.nianling" />
            </el-form-item>

            <el-form-item label="手机号">
              <el-input v-model="userInfo.dianhuahaoma" />
            </el-form-item>

                     
            <el-form-item label="宿舍">
              <el-input v-model="userInfo.sushe" />
            </el-form-item>

              <el-form-item label="楼栋">
              <el-input v-model="userInfo.loudong" />
            </el-form-item>
            
            <el-form-item label="院系">
              <el-input v-model="userInfo.yuanxi" />
            </el-form-item>

          </template>
          
          <template v-if="role === '宿管'">
            <el-form-item label="宿管账号">
              <el-input v-model="userInfo.suguanzhanghao" :disabled="true" />
            </el-form-item>
<!-- 
            <el-form-item label="用户名">
              <el-input v-model="userInfo.suguanzhanghao" :disabled="true" />
            </el-form-item> -->

            <el-form-item label="姓名">
              <el-input v-model="userInfo. suguanxingming" />
            </el-form-item>
            
            <el-form-item label="性别">
              <el-input v-model="userInfo. xingbie" />
            </el-form-item>

            <el-form-item label="管理楼栋号">
              <el-input v-model="userInfo.loudong" />
            </el-form-item>

            <el-form-item label="手机号">
              <el-input v-model="userInfo.dianhuahaoma" />
            </el-form-item>
          </template>
          
          <el-form-item>
            <el-button type="primary" @click="submitForm">保存修改</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { userAPI, fileAPI } from '@/utils/api'

const sessionTable = localStorage.getItem('sessionTable') || ''
const role = localStorage.getItem('role') || ''
const headers = reactive({
  token: localStorage.getItem('Token') || ''
})

const userInfo = ref({
  id: '',          // 学号/工号（根据角色）
  xueshengzhanghao: '', // 学生用户名（对应学生模板）
  suguanzhanghao: '',   // 宿管用户名（对应宿管模板）
  xueshengxingming: '', // 学生姓名（对应学生模板）
  suguanxingming: '',   // 宿管姓名（对应宿管模板）
  xingbie: '',     // 性别
  dianhuahaoma: '',// 手机号
  nianling: '',    // 年龄（学生特有）
  
  // 学生特有字段
  banji: '',       // 宿舍（对应学生模板）------这里要改成宿舍  在后端  表中是sushe
  yuanxi: '',      // 院系（对应学生模板）
})

const formRef = ref(null)
const originalInfo = ref({})

// 获取用户信息
const getUserInfo = async () => {
  try {
    const data = await userAPI.getSession(sessionTable)
    
    if (data && data.code === 0) {
      userInfo.value = { ...data.data }
      originalInfo.value = { ...data.data }
    } else {
      ElMessage.error(data.msg || '获取个人信息失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('获取个人信息失败')
  }
}

// 提交表单
const submitForm = async () => {
  try {
    const data = await userAPI.update(sessionTable, userInfo.value)
    
    if (data && data.code === 0) {
      ElMessage.success('保存成功')
      getUserInfo()
    } else {
      ElMessage.error(data.msg || '保存失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('保存失败')
  }
}

// 重置表单
const resetForm = () => {
  userInfo.value = { ...originalInfo.value }
}

// 头像选择后处理
const handleAvatarChange = async (file) => {
  const isJPG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png'
  const isLt2M = file.raw.size / 1024 / 1024 < 2
  
  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG 或 PNG 格式!')
    return false
  }
  
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  
  try {
    const data = await userAPI.updateImg(sessionTable, file.raw)
    if (data && data.code === 0) {
      userInfo.value.headImg = data.data
      ElMessage.success('头像上传成功')
    } else {
      ElMessage.error(data.msg || '头像上传失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('头像上传失败')
  }
}

onMounted(() => {
  getUserInfo()
})
</script>

<style lang="scss" scoped>
.center-container {
  padding: 20px;
  
  .center-card {
    max-width: 800px;
    margin: 0 auto;
    
    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    
    .user-info {
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .avatar-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-bottom: 20px;
        
        .upload-btn {
          margin-top: 10px;
        }
      }
      
      .user-form {
        width: 100%;
        max-width: 500px;
      }
    }
  }
}
</style> 